package com.gurid.service.ucenter.controller.api;

import com.gurid.common.base.result.R;
import com.gurid.common.base.result.ResultCode;
import com.gurid.common.base.util.JwtInfo;
import com.gurid.common.base.util.JwtUtils;
import com.gurid.service.base.dto.MemberDto;
import com.gurid.service.base.exception.GuridException;
import com.gurid.service.ucenter.entity.vo.LoginVo;
import com.gurid.service.ucenter.entity.vo.RegisterVo;
import com.gurid.service.ucenter.service.MemberService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author Gurid
 * @since 2024-06-02
 */
@Tag(name = "ApiMemberController", description = "会员管理")
@RestController
@RequestMapping("/api/ucenter/member")
//@CrossOrigin
@Slf4j
public class ApiMemberController {

    @Autowired
    private MemberService memberService;

    @Operation(description = "会员注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo) {
        memberService.register(registerVo);
        return R.ok().message("注册成功");
    }

    @Operation(description = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody LoginVo loginVo) {
        String token = memberService.login(loginVo);
        System.out.println("token: " + token);
        return R.ok().data("token", token).message("登录成功");
    }

    @Operation(description = "根据token获取登录信息")
    @GetMapping("get-login-info")
    public R getLoginInfo(HttpServletRequest request) {

        try {
            System.out.println("-=-=-===-=-=已经接收到了请求，开始解析cookie-=-=-=-=-=-=-=-");
            JwtInfo jwtInfo = JwtUtils.getMemberIdByJwtToken(request);
            System.out.println("-=-=-=-=-=-=-=-解析cookie完毕=-=-=-=-=-=-=-");
            System.out.println("id: " + jwtInfo.getId() + ",  nickname: " + jwtInfo.getNickname() + ",  avatar: " + jwtInfo.getAvatar());
            return R.ok().data("userInfo", jwtInfo);
        } catch (Exception e) {
            log.error("解析用户信息失败" + e.getMessage());
            throw new GuridException(ResultCode.FETCH_USERINFO_ERROR);
        }
    }

    @Operation(summary = "根据会员id查询会员信息")
    @GetMapping("inner/get-member-dto/{memberId}")
    public MemberDto getMemberDtoByMemberId(
            @Parameter(description = "会员id", required = true)
            @PathVariable("memberId") String memberId) {

        MemberDto memberDto = memberService.getMemberDtoByMemberId(memberId);
        return memberDto;
    }
}
